package com.hui.dbmigrator.util;

public class SQLFormatter {

    private static final String KEYWORDS = "(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|FROM|WHERE|AND|OR|JOIN|INNER|OUTER|LEFT|RIGHT|FULL|ON|GROUP BY|HAVING|ORDER BY|LIMIT|VALUES|SET)";

    public static String format(String sql) {
        if (sql == null) return "";

        // 统一换行符
        sql = sql.replaceAll("\r\n", "\n")
                .replaceAll("\r", "\n");

        // 关键字换行和缩进
        sql = sql.replaceAll("(?i)" + KEYWORDS, "\n$1");

        // 处理逗号
        sql = sql.replaceAll(",", ",\n  ");

        // 处理括号
        sql = sql.replaceAll("\\(", "(\n  ")
                .replaceAll("\\)", "\n)");

        // 移除多余的空行
        sql = sql.replaceAll("\n\\s+\n", "\n");

        return sql.trim();
    }
}
